﻿using Common.Logging;
using System;
using System.Collections.Generic;
using System.DirectoryServices;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Wicresoft.EKA.NRemedy;

namespace Wicresoft.Task.EmployeeSync
{
    class IncrementalPeopleInfo : IIncrementalPeopleInfo
    {
        private static readonly ILog logger = LogManager.GetCurrentClassLogger();
        private ARLoginContext context = null;
        private ARProxy<CTMPeopleModel> proxy = null;

        public IncrementalPeopleInfo(ARLoginContext context)
        {
            this.context = context;
            this.proxy = new ARProxy<CTMPeopleModel>(context);
        }

        public IList<CTMPeopleModel> GetChangedList()
        {
            var listPeople = new List<CTMPeopleModel>();
            var Path = "LDAP://ekaitsm.com/OU=Department1,OU=Company,DC=ekaitsm,DC=com";
            var Username = "Administrator";
            var Password = "Pass01!!";

            var dateAfterChangeString = ADHelper.GetDateString(DateTime.Now.AddDays(-50)); //DateTime.Now.AddDays(-50).ToString("yyyymmddhhmmss") + ".0Z";

            try
            {
                using (var de = new DirectoryEntry(Path, Username, Password))
                {
                    using (var searcher = new DirectorySearcher())
                    {

                        searcher.SearchRoot = de;
                        searcher.Filter = "(&(objectClass=user)(whenChanged>=" + dateAfterChangeString + "))";
                        searcher.SearchScope = SearchScope.Subtree;

                        //searcher.PropertiesToLoad.Add("name");
                        //searcher.PropertiesToLoad.Add("description");
                        //searcher.PropertiesToLoad.Add("givenName");
                        //searcher.PropertiesToLoad.Add("wWWHomePage");

                        //searcher.Sort = new SortOption("givenName", SortDirection.Ascending);

                        SearchResultCollection results = searcher.FindAll();
                        foreach (SearchResult result in results)
                        {
                            listPeople.Add(ADHelper.ConvertFromDirectory(result.GetDirectoryEntry(),logger));
                        }
                    }
                }
            }

            catch (COMException ex)
            {
                logger.Error(ex);
            }
            return listPeople;
        }

        public void HandlerPeople(CTMPeopleModel source, CTMPeopleModel destination)
        {
            List<CTMPeopleModel> list = new List<CTMPeopleModel>();
            //list.OrderBy()
            throw new NotImplementedException();
        }

        public bool IsFull
        {
            get { return false; }
        }

        public void HandlerAll()
        {
            var list = this.GetChangedList();
            CTMPeopleModel tempModel = null;


            foreach (var item in list)
            {
                //从数据库相应的获取一下，只有有变化，只有有必要去更新，才去更新。
                tempModel = GetCTMPeopleByIdentify(item.RemedyLoginID);

                if (tempModel == null)
                {
                    Create(item);
                }
                else if (item.ProfileStatus == CTMPeopleModel.ProfileStatus_Enum.Delete)
                {
                    Delete(tempModel);
                }
                else
                {
                    Modify(item, tempModel);
                }
            }
        }


        public bool Equals(CTMPeopleModel source, CTMPeopleModel destination)
        {
            throw new NotImplementedException();
        }


        public void Create(CTMPeopleModel source)
        {
            if (source.ProfileStatus == CTMPeopleModel.ProfileStatus_Enum.Enabled && !string.IsNullOrWhiteSpace(source.RemedyLoginID))
                proxy.CreateEntry(source);
        }

        public void Modify(CTMPeopleModel source, CTMPeopleModel destination)
        {


            if (source.Company != destination.Company ||
                source.Department != destination.Department ||
                source.FullName != destination.FullName ||
                source.InternetEmail != destination.InternetEmail ||
                source.Organization != destination.Organization ||
                source.PhoneNumberBusiness != destination.PhoneNumberBusiness ||
                source.Site != destination.Site
                )
            {
                if (source.RemedyLoginID != destination.RemedyLoginID) throw new InvalidOperationException("Can not change the login ID");
                source.PersonID = destination.PersonID;
                proxy.SetEntry(source);
            }

        }

        public void Delete(CTMPeopleModel detination)
        {
            detination.ProfileStatus = CTMPeopleModel.ProfileStatus_Enum.Delete;
            proxy.SetEntry(detination);
            proxy.DeleteEntry(detination);
        }


        public CTMPeopleModel GetCTMPeopleByIdentify(params string[] identifies)
        {
            return proxy.GetListEntry(CTMPeopleModel.RemedyLoginID_Name.S() + "=" + identifies[0].D(),
                new List<uint>() 
                {
                    CTMPeopleModel.FirstName_ID,
                    CTMPeopleModel.LastName_ID,
                    CTMPeopleModel.FullName_ID,
                    CTMPeopleModel.ProfileStatus_ID,
                    CTMPeopleModel.RemedyLoginID_ID,
                    CTMPeopleModel.Company_ID,
                    CTMPeopleModel.Organization_ID,
                    CTMPeopleModel.Department_ID,
                    CTMPeopleModel.InternetEmail_ID,
                    CTMPeopleModel.PhoneNumberBusiness_ID,
                }).FirstOrDefault();
        }
    }
}
